package cn.net.autocode.platform.entrance;

import cn.net.autocode.dbManager.Dao;
import cn.net.autocode.platform.config.SpringProfileConfig;
import cn.net.autocode.platform.design.webclient.AcWebClient;
import cn.net.autocode.platform.viewEngine.AutoCodeThymeleaf;
import com.alibaba.fastjson2.JSONObject;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.View;
import java.util.Map;

@Controller
@RequestMapping("platform/page")
public class PageEntrance {

    private final SpringProfileConfig profileConfig;

    private final Dao dictDao;

    private final AcWebClient acWebClient;

    public PageEntrance(SpringProfileConfig profileConfig, @Qualifier("dictDao")Dao dictDao, AcWebClient acWebClient) {
        this.profileConfig = profileConfig;
        this.dictDao = dictDao;
        this.acWebClient = acWebClient;
    }

    @RequestMapping("/{path1}/{path2}")
    public ModelAndView pathView(@PathVariable("path1") String path1, @PathVariable("path2") String path2, HttpServletRequest request) {
        ModelAndView mav = new ModelAndView();
        JSONObject params = this.preRequest(request);
        for (Map.Entry<String, Object> entry : params.entrySet()) {
            mav.addObject(entry.getKey(), entry.getValue());
        }

        String html;
        if(profileConfig.getProfile().equals("dev")){
            JSONObject param = new JSONObject();
            param.put("categoryCode",path1);
            param.put("code",path2);
            html = acWebClient.pageView(param);
        }else{
            html = dictDao.queryValue("select ac_page_versions.html from ac_page,ac_page_versions where ac_page.id=ac_page_versions.page_id and ac_page.version=ac_page_versions.version and category_code=? and code=?", String.class,path1,path2);
        }
        View view = new AutoCodeThymeleaf(html);
        mav.setView(view);
        return mav;
    }

    private JSONObject preRequest(HttpServletRequest request){
        JSONObject json = new JSONObject();
        Map<String,String[]> map = request.getParameterMap();
        for(Map.Entry<String,String[]> entry:map.entrySet()){
            if(entry.getValue().length>1){
                json.put(entry.getKey(),entry.getValue());
            }else if(entry.getValue().length==1){
                json.put(entry.getKey(),entry.getValue()[0]);
            }
        }
        return json;
    }

}
